<route lang="yaml">
  meta:
    title: 报警信息
</route>

<script setup>
import axios from 'axios'
import { onMounted, ref } from 'vue'

const searchSerial = ref('')
const selectedUnit = ref('')
const currentPage = ref('1')
const pageSize = ref(5)

const totalUnits = ref(100)
const totalNum = ref(0)
const devices = ref([])
const customerCode = ref('') // 选中单位的 customerCode
const tableData = ref()
const unReadNum = ref()

const units = ref([])

async function fetchData() {
  console.log('参数', customerCode.value)
  const params = {
    // customerRegion: adminUserRegion,
    customerCode: 'CUS20241219170549', // customerCode.value,
    pageNum: currentPage.value,
    pageSize: pageSize.value,
  }
  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/feedback/getHikFaultStatistics')
    console.log('返回数据', response.data)
    totalNum.value = response.data.data.rows.length
    devices.value = response.data.data.rows
  }
  catch (error) {
    console.error('请求失败:', error)
  }
}
async function fetchUnReadData() {
  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/feedback/findUnreadBackend', {
      feedbackType: 1,
    })
    if (response.data) {
      unReadNum.value = response.data.data.unreadNum
    }
  }
  catch (error) {
    console.error('获取数据时出错:', error)
  }
}
async function fetchTableData({ pageNum = '1' }) {
  fetchUnReadData()
  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/feedback/findAllByConditionToObserve', {
      pageNum,
      pageSize: pageSize.value,
      feedbackType: 1, // 1预警2故障
      feedbackState: 1,
      feedbackHikDeviceSerial: searchSerial.value,
      feedbackClassification: 1,
    })
    if (response.data) {
      console.log('获取故障数据', response.data)
      tableData.value = response.data.data.rows
      totalNum.value = response.data.data.total
      console.log('totalNum', totalNum.value)
    }
  }
  catch (error) {
    console.error('获取数据时出错:', error)
  }
}
function handlePageChange(page) {
  currentPage.value = page
  fetchTableData({ pageNum: currentPage.value })
}

// 从 localStorage 获取用户区域
const adminUserRegion = localStorage.getItem('adminUserRegion')

// 获取单位数据的函数
async function fetchCustomerData() {
  try {
    const params = {
      // customerRegion: adminUserRegion,
      pageNum: '1',
      pageSize: '100',
    }

    // 发起 POST 请求
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/customer/findAllByCondition', params)
    // 将单位数据填充到下拉框中
    units.value = response.data.data.rows
    if (units.value.length > 0) {
      selectedUnit.value = units.value[0].customerName // 默认选中第一个单位名称
      customerCode.value = units.value[0].customerCode // 设置对应的单位代码
      console.log('默认选中的单位:', selectedUnit.value)
      console.log('默认选中的单位代码:', customerCode.value)
    }
  }
  catch (error) {
    console.error('获取单位数据失败:', error)
  }
}

// 用户选择单位时的回调函数
function handleUnitChange(selectedCustomerName) {
  const selectedUnit = units.value.find(item => item.customerName === selectedCustomerName)
  if (selectedUnit) {
    customerCode.value = selectedUnit.customerCode // 设置 customerCode
    console.log('选中的单位代码:', customerCode.value)
  }
}

// 点击“搜索”按钮时触发查询
function handleSearch() {
  currentPage.value = 1 // 重置到第一页
  fetchTableData({})
}
// 新增对话框
const isDialogVisible = ref(false)

const feedbackInfo = ref('') // 保存当前选中的反馈
const workOrderCreateRemarks = ref('')
const dialogTitle = ref('')
function handle(row) {
  feedbackInfo.value = row
  console.log(feedbackInfo.value)
  dialogTitle.value = '处置'
  isDialogVisible.value = true // 打开对话框
}
function reject(row) {
  feedbackInfo.value = row
  dialogTitle.value = '驳回'
  isDialogVisible.value = true // 打开对话框
}
function liuguan(row) {
  feedbackInfo.value = row
  dialogTitle.value = '留观'
  isDialogVisible.value = true // 打开对话框
}
// 生成工单
async function createWorkOrder() {
  const {
    feedbackCode,
    customerCode,
    customerName,
    customerUserName,
    customerUserPhone,
    feedbackContent,
    feedbackAddress,
    feedbackCity,
    feedbackProvince,
    feedbackRegion,
    feedbackLongitude,
    feedbackLatitude,
    createDate,
    feedbackType,
    feedbackImgFile,
    feedbackVideoFile,
    feedbackVoiceFile,
  } = feedbackInfo.value
  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/workOrder/createWorkOrder', {
      feedbackCode,
      customerCode,
      customerName,
      customerUserName,
      customerUserPhone,
      adminUserCode: 'ADMIN-USER20241031211423',
      workOrderContent: feedbackContent,
      workOrderImgFile: feedbackImgFile,
      feedbackDate: createDate,
      feedbackProvince,
      feedbackCity,
      feedbackRegion,
      feedbackAddress,
      feedbackLongitude,
      feedbackLatitude,
      feedbackType,
      workOrderVideoFile: feedbackVideoFile,
      workOrderVoiceFile: feedbackVoiceFile,
      workOrderCreateRemarks: workOrderCreateRemarks.value,
    })

    console.log('生成工单结果：', response.data)
    if (response.data.code === 200) {
      console.log('生成工单结果：', response.data)
      window.location.reload()
    }
  }
  catch (error) {
    console.error('获取数据时出错:', error)
  }
}

// 确认处置/驳回
async function confirmAdd() {
  let feedbackState = 4
  if (dialogTitle.value === '处置') {
    feedbackState = 4
  }
  else if (dialogTitle.value === '驳回') {
    feedbackState = 2
  }
  else {
    feedbackState = 3
  }
  isDialogVisible.value = false
  const { feedbackCode } = feedbackInfo.value
  console.log(`备注: ${workOrderCreateRemarks.value}, 工单号1: ${feedbackCode},feedbackState:${feedbackState}`)
  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/feedback/stateUp', {
      feedbackCode,
      feedbackState,
      feedbackRemarks: workOrderCreateRemarks.value,
    })

    if (response.data.code === 200) {
      console.log('已处置/驳回：', response.data)
      // 生成工单
      if (feedbackState === 4) {
        createWorkOrder()
      }
      // window.location.reload()
    }
  }
  catch (error) {
    console.error('获取数据时出错:', error)
  }
}
// 修改已读
async function upAppointUnreadBackend(feedbackCode) {
  try {
    const response = await axios.post('https://www.cqwuyang.cn/ElectricManageService/feedback/upAppointUnreadBackend', {
      feedbackCode,
    })
    console.log('已读：', response.data)
    if (response.data.code === 200) {
      console.log('已读：', response.data)
      currentPage.value = 1
      await fetchTableData({})
    }
  }
  catch (error) {
    console.error('获取数据时出错:', error)
  }
}
const router = useRouter()
function openReportPage(row) {
  console.log(row.feedbackCode)
  const to = router.resolve({
    name: 'report-details',
    params: { id: row.feedbackCode },
  })
  upAppointUnreadBackend(row.feedbackCode)
  const httpUrl = to.href.replace(/^https:\/\//, 'http://')
  window.open(httpUrl, '_blank')
  // window.open(to.href, '_blank')
}

function formatState(row, column, cellValue) {
  switch (cellValue) {
    case 1:
      return '待处理'
    case 2:
      return '驳回'
    case 3:
      return '留观'
    case 4:
      return '已处置'
    default:
      return '未知'
  }
}
function formatType(row, column, cellValue) {
  switch (cellValue) {
    case 1:
      return '预警'
    case 2:
      return '故障'
    default:
      return '未知'
  }
}
// 打开弹框
function resetSelection() {
  workOrderCreateRemarks.value = null
}

onMounted(async () => {
  // await fetchCustomerData() // 等待 fetchCustomerData 完成
  // await fetchData()// 然后执行 fetchData
  await fetchTableData({})
})
</script>

<template>
  <div class="device-dashboard">
    <!-- 左侧搜索区域 -->
    <div class="sidebar">
      <el-input v-model="searchSerial" placeholder="请输入设备序列号" clearable />
      <el-button type="primary" class="mt-4" @click="handleSearch">
        搜索
      </el-button>
    </div>

    <!-- 主内容区域 -->
    <div class="content">
      <!-- 数量信息 -->
      <div class="device-info">
        <div class="info-item">
          <div class="circle">
            {{ totalNum }}
          </div>
          <p>全部报警</p>
        </div>
        <div class="info-item">
          <div class="circle">
            {{ 0 }}
          </div>
          <p>今日报警</p>
        </div>
      </div>

      <!-- 设备列表 -->
      <el-table
        :data="tableData" border class="table" style="width: 100%; cursor: pointer;"
        @row-click="openReportPage"
      >
        <!-- <el-table-column prop="createDate" label="最新报警" align="center" /> -->
        <el-table-column prop="createDate" label="最新报警" align="center">
          <template #default="{ row }">
            <span v-if="row.feedbackGlanceServer === 0" class="red-dot" />
            <span>{{ row.createDate }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="feedbackHikNewDate" label="首次报警" align="center" />
        <el-table-column prop="feedbackContent" label="事件源" align="center" />
        <el-table-column prop="feedbackType" label="报警类型" :formatter="formatType" align="center" />
        <el-table-column prop="feedbackHikDeviceType" label="设备类型" align="center" />
        <el-table-column prop="feedbackHikDeviceSerial" label="序列号" align="center" />
        <el-table-column prop="customerName" label="所属单位" align="center" />
        <el-table-column prop="feedbackState" label="处理状态" :formatter="formatState" align="center" />
        <el-table-column prop="actions" label="操作" align="center">
          <template #default="{ row }">
            <el-button
              type="text" size="small" class="action-button"
              @click="(event) => { event.stopPropagation(); reject(row); }"
            >
              驳回
            </el-button>
            <el-button
              v-if="row.observe === 1" type="text" size="small" class="action-button"
              @click="changeObserve(row)"
            >
              留观
            </el-button>
            <el-button
              v-else type="text" size="small" class="action-button"
              @click="(event) => { event.stopPropagation(); liuguan(row); }"
            >
              留观
            </el-button>
            <el-button
              type="text" size="small" class="action-button"
              @click="(event) => { event.stopPropagation(); handle(row); }"
            >
              处置
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 对话框 -->
      <el-dialog v-model="isDialogVisible" :title="dialogTitle" @open="resetSelection">
        <!-- 对话框内容 -->
        <p><strong>请填写备注：</strong></p>
        <el-input
          v-model="workOrderCreateRemarks" style="width: 600px;" type="textarea" placeholder="请填写备注"
          clearable
        />
        <template #footer>
          <el-button @click="isDialogVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="confirmAdd">
            确定
          </el-button>
        </template>
      </el-dialog>
      <!-- 分页 -->
      <el-pagination
        size="small" background layout="prev, pager, next" :total="totalNum" class="mt-4"
        :current-page="currentPage" :default-page-size="pageSize" @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped>
.red-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  margin-left: 5px;
  background-color: red;
  border-radius: 50%;
}

.device-dashboard {
  display: flex;
}

.sidebar {
  width: 20%;
  padding: 20px;
  border-right: 1px solid #ebebeb;
}

.content {
  width: 80%;
  padding: 20px;
}

.device-info {
  display: flex;
  gap: 500px;
  justify-content: flex-start;
  margin-bottom: 20px;
}

.info-item {
  text-align: center;
}

.circle {
  width: 80px;
  height: 80px;
  margin: 0 auto;
  font-size: 24px;
  font-weight: bold;
  line-height: 80px;
  background-color: #bab9b9;
  border-radius: 50%;
}

.device-card {
  margin-bottom: 20px;
}

.device-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
